#include "bsp_uart.h"
#include "SEGGER_RTT.h"
#include "freertos.h"

TxHandle_t htx1;
uint8_t txfifo1_buf[TXFIFO_LENGTH*4];
RxHandle_t hrx1;

TxHandle_t htx2;
uint8_t txfifo2_buf[TXFIFO_LENGTH];
RxHandle_t hrx2;

TxHandle_t htx3;
uint8_t txfifo3_buf[TXFIFO_LENGTH];
RxHandle_t hrx3;


void UART1_RS485_CallBack(int args)
{
	if (args > 0)
		HAL_GPIO_WritePin(RS485_DE_GPIO_Port, RS485_DE_Pin, GPIO_PIN_SET);
	else
		HAL_GPIO_WritePin(RS485_DE_GPIO_Port, RS485_DE_Pin, GPIO_PIN_RESET);
}

void UART_BSP_Init(void)
{
	

	//创建接收句柄
	UART_RxHandle_CreateStatic(&huart4, &hrx1);
	UART_RxHandle_CreateStatic(&huart3, &hrx2);
	UART_RxHandle_CreateStatic(&huart1, &hrx3);

	//创建发送句柄
	UART_TxHandle_CreateStatic(&huart4, &htx1, txfifo1_buf, TXFIFO_LENGTH*4);
	UART_TxHandle_CreateStatic(&huart3, &htx2, txfifo2_buf, TXFIFO_LENGTH);
	UART_TxHandle_CreateStatic(&huart1, &htx3, txfifo3_buf, TXFIFO_LENGTH);

	//绑定钩子
	htx3.uartTxHook = UART1_RS485_CallBack;

	//初始化串口
	User_USARTx_Init(&hrx1, 4);
	User_USARTx_Init(&hrx2, 3);
	User_USARTx_Init(&hrx3, 1);
}

/**
 * @brief  Tx Transfer completed callbacks.
 * @param  huart  Pointer to a UART_HandleTypeDef structure that contains
 *                the configuration information for the specified UART module.
 * @retval None
 */
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
	TxHandle_TxCpltCallback(&htx1);
	TxHandle_TxCpltCallback(&htx2);
	TxHandle_TxCpltCallback(&htx3);
}


void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	BaseType_t xHigherPriorityTaskWoken = pdFALSE;
	uint32_t ulValue;
	if (Size == 0) return;

	if(huart == hrx1.huart)
	{
		RxHandle_RxEventCallback(&hrx1, Size); //开启下一轮接收
		ulValue = 1<<0;
	}
	else if(huart == hrx2.huart)
	{
		RxHandle_RxEventCallback(&hrx2, Size);
		ulValue = 1<<1;
	}
	else if(huart == hrx3.huart)
	{
		RxHandle_RxEventCallback(&hrx3, Size);
		ulValue = 1<<2;
	}
	
	if (ulValue != 0)//通知任务来处理数据，没有RTOS可以用Flag代替	
	{
		xTaskNotifyFromISR( MsgHandleTaskHandle,
							ulValue,
							eSetBits,
		                	&xHigherPriorityTaskWoken); 
	}
	portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}



